package com.example.gfsquadwebviewproject.presenter.http.get;

import android.content.Context;

import com.example.gfsquadwebviewproject.data.Constant;
import com.example.gfsquadwebviewproject.util.L;
import com.example.gfsquadwebviewproject.util.NetworkUtils;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2019/1/2 0002.
 */
public  class OkhttpGet implements IGet {

    IGetRequest iGetRequest;
    Context context;

    public OkhttpGet(IGetRequest iGetRequest, Context context){
        this.iGetRequest = iGetRequest;
        this.context = context;
    }

    @Override
    public void get(String url, final int type){

        L.d("Context","地址："+url);
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(url).build();

        /**
         * 有网时候的缓存 10s
         */
        final Interceptor NetCacheInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Response response = chain.proceed(request);
                int onlineCacheTime = 10*1;//在线的时候的缓存过期时间，如果想要不缓存，直接时间设置为0
                return response.newBuilder()
                        .header("Cache-Control", "public, max-age="+onlineCacheTime)
                        .removeHeader("Pragma")
                        .build();
            }
        };
        /**
         * 没有网时候的缓存 24h
         */
        final Interceptor OfflineCacheInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                if (!NetworkUtils.isNetwork(context)) {
                    int offlineCacheTime = 60*60*24;//离线的时候的缓存的过期时间 24小时
                    request = request.newBuilder()
//                        .cacheControl(new CacheControl
//                                .Builder()
//                                .maxStale(60,TimeUnit.SECONDS)
//                                .onlyIfCached()
//                                .build()
//                        ) 两种方式结果是一样的，写法不同
                            .header("Cache-Control", "public, only-if-cached, max-stale=" + offlineCacheTime)
                            .build();
                }
                return chain.proceed(request);
            }
        };

        //setup cache 随app删除而删除的缓存文件
        File httpCacheDirectory = new File(context.getCacheDir(), "okhttpCache");
        int cacheSize = 100 * 1024 * 1024; // 100 MiB
        Cache cache = new Cache(httpCacheDirectory, cacheSize);
        OkHttpClient client = new OkHttpClient.Builder()
                .addNetworkInterceptor(NetCacheInterceptor)
                .addInterceptor(OfflineCacheInterceptor)
                .cache(cache)
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15,TimeUnit.SECONDS)
                .build();

        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败的处理
                try {
                    if (iGetRequest !=null) {
                        iGetRequest.requestBackMsg(e.getMessage(), type, 0);
                    }
                } catch (Exception ex) {
                    L.d("Context","OKHttpGetTest onFailure:"+ex);
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    //string只能取一次
                    String string = response.body().string();
                    if (response.networkResponse() != null) {
                        //"network,网络状态:"+NetworkUtils.isNetwork(context);
                    }
                    else if (response.cacheResponse() != null) {
                        if (Constant.isInternet) {
                            //cache,网络状态:"+NetworkUtils.isNetwork(context);
                        } else {
                            //"cache(no network),网络状态:"+NetworkUtils.isNetwork(context);
                        }
                    }

                    if (iGetRequest!=null) {
                        iGetRequest.requestBackMsg(string, type, 1);
                    }

                }
                else {
                    iGetRequest.requestBackMsg("response.isSuccessful()", type, 0);
                }
            }
        });

    }

}
